<script setup>
import { reactive, ref, computed } from "vue";
import { validatePassword } from "@/utils/validate";
import { changePasswordApi, logoutApi } from "@/api/user";
import { ElMessage } from "element-plus";
import { logout, isLogin, getUserInfo } from "@/utils/index";
import { useRouter } from "vue-router";
import { useUserStore } from "@/store/user";
const router = useRouter();
const userStore = useUserStore();

const formRef = ref();

const form = reactive({
  password: "",
  new_password: "",
  new_password2: "",
});

const rules = {
  password: [{ validator: validatePassword, trigger: "blur" }],
  new_password: [{ validator: validatePassword, trigger: "blur" }],
  new_password2: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value != form.new_password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

const user_id = computed(() => getUserInfo().user_id);
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate();
  const res = await changePasswordApi({ ...form, user_id: user_id.value });
  if (res.data.status === 200) {
    ElMessage({
      message: "密码修改成功，请重新登录。即将跳转至登录页……",
      type: "success",
    });
    setTimeout(() => {
      logoutApi();
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("userInfo");
      userStore.setIsLogin(false);
      router.replace("/login");
    }, 1000);
  } else {
    ElMessage({
      message: res.data.message,
      type: "error",
    });
  }
};

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
<template>
  <div>
    <el-form ref="formRef" :model="form" label-width="100px" :rules="rules">
      <el-form-item
        label="旧密码"
        prop="password"
        :rules="[{ required: true, message: '请填写旧密码' }]"
      >
        <el-input v-model="form.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="新密码"
        prop="new_password"
        :rules="[{ required: true, message: '请填写新密码' }]"
      >
        <el-input
          v-model="form.new_password"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item
        label="重复新密码"
        prop="new_password2"
        :rules="[{ required: true, message: '请再次填写新密码' }]"
      >
        <el-input
          v-model="form.new_password2"
          type="password"
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped></style>
